﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>采购发票修改</title>
    <link rel="stylesheet" href="~/lib/layui/css/layui.css">
    <link href="~/lib/layui/css/layui.css" rel="stylesheet" />
    <style>
        body {
            background-color: #f2f2f2;
            padding: 20px;
        }

        .invoice-container {
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }

        .form-title {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
            color: #333;
        }

        .form-table {
            width: 100%;
            margin-bottom: 15px;
        }

            .form-table td {
                padding: 10px 15px;
                vertical-align: top;
            }

        .form-actions {
            text-align: center;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }

        .layui-form-label {
            width: 100px;
        }

        .layui-input-block {
            margin-left: 130px;
        }

        .layui-form-item {
            margin-bottom: 15px;
        }

        .required:before {
            content: '*';
            color: red;
            margin-right: 4px;
        }

        /* 对话框样式 */
        .dialog-body {
            padding: 15px;
            overflow-y: auto;
            max-height: 70vh;
        }
        /* -------------------------- */
        .material-info-section {
            margin: 20px 0;
            border: 1px solid #ddd;
            padding: 15px;
            border-radius: 5px;
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .material-table {
            width: 100%;
            border-collapse: collapse;
        }

            .material-table th, .material-table td {
                border: 1px solid #ddd;
                padding: 8px;
                text-align: center;
            }

            .material-table th {
                background-color: #f2f2f2;
            }

            .material-table input {
                width: 100%;
                box-sizing: border-box;
                padding: 5px;
            }

        .btn {
            padding: 5px 10px;
            cursor: pointer;
            border: none;
            border-radius: 3px;
        }

        .btn-primary {
            background-color: #4CAF50;
            color: white;
        }

        .btn-save {
            background-color: #2196F3;
            color: white;
            padding: 8px 15px;
        }

        .btn-delete {
            background-color: #f44336;
            color: white;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.4);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 5% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 900px;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-bottom: 10px;
            border-bottom: 1px solid #ddd;
        }

        .close {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }

        .search-bar {
            margin: 15px 0;
            display: flex;
        }

            .search-bar input {
                flex: 1;
                padding: 8px;
                margin-right: 10px;
            }

        .material-select-table {
            width: 100%;
            border-collapse: collapse;
        }

            .material-select-table th, .material-select-table td {
                border: 1px solid #ddd;
                padding: 8px;
                text-align: center;
            }

        .pagination {
            margin-top: 15px;
            text-align: right;
        }

            .pagination input {
                width: 50px;
                text-align: center;
                margin: 0 5px;
            }
    </style>

</head>

<body>
    <div class="layui-container invoice-container">
        <h2 class="form-title">采购发票</h2>
        <span class="layui-breadcrumb">
            <a href="GetProcurements">采购发票列表</a>
            <a href="ProcurementsAdd">查看采购发票</a>
        </span>
        <form class="layui-form" id="purchaseInvoiceForm" lay-filter="editForm">
            @* <input type="hidden" name="peid"> *@
            <input type="hidden" id="peid" name="peid"> <!-- 示例 -->
            <table class="form-table">
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label required">单据编码：</label>
                            <div class="layui-input-block">
                                <input readonly type="text" name="documentCode" placeholder="请输入单据编码" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label required" readonly>业务类型：</label>
                            <div class="layui-input-block">
                                <select readonly name="documentid" lay-verify="required">
                                    <option value="">请选择业务类型</option>
                                    <option value="1" selected>零部件发票</option>
                                    <option value="2">原材料发票</option>
                                    <option value="3">服务类发票</option>
                                </select>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label required">供应商：</label>
                            <div class="layui-input-block">
                                <div class="layui-input-inline" style="width: 80%">
                                    <input readonly type="text" name="supid" placeholder="请选择供应商" autocomplete="off" class="layui-input">
                                </div>
                                @* <div class="layui-input-inline" style="width: 20%"> *@
                                @*     <button type="button" class="layui-btn layui-btn-primary" onclick="selectSupplier()"> *@
                                @*         <i class="layui-icon">&#xe615;</i> 选择 *@
                                @*     </button> *@
                                @* </div> *@
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label required">开票日期：</label>
                            <div class="layui-input-block">
                                <input readonly type="text" name="invoiceDate" id="invoiceDate" placeholder="请选择开票日期" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label required">单据日期：</label>
                            <div class="layui-input-block">
                                <input type="text" name="documentTime" id="documentTime" value="2025-03-28" autocomplete="off" class="layui-input" readonly>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">操作员：</label>
                            <div class="layui-input-block">
                                <input type="text" name="operator" value="njrsun" autocomplete="off" class="layui-input" readonly>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">税号：</label>
                            <div class="layui-input-block">
                                <input readonly type="text" name="taxNumber" placeholder="请输入税号" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">红字蓝字：</label>
                            <div class="layui-input-block">
                                <select readonly name="redandblue">
                                    <option value="1" selected>蓝字</option>
                                    <option value="2">红字</option>
                                </select>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">单据状态: </label>
                            <div class="layui-input-block">
                                <select name="documentStuct" lay-verify="required">
                                    <option value="true">开立</option>
                                    <option value="false">审核</option>
                                </select>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">审核员：</label>
                            <div class="layui-input-block">
                                <input readonly type="text" name="auditor" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">发票类型：</label>
                            <div class="layui-input-block">
                                <select name="invoiceType" class="layui-readonly">
                                    <option value="">请选择发票类型</option>
                                    <option value="1">增值税专用发票</option>
                                    <option value="2">普通发票</option>
                                    <option value="3">电子发票</option>
                                </select>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">发票金额：</label>
                            <div class="layui-input-block">
                                <input readonly type="text" name="invoiceAmount" placeholder="0.00" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">业务状态：</label>
                            <div class="layui-input-block">
                                <select name="businessStuct">
                                    <option value="1" selected>正常</option>
                                    <option value="2">异常</option>
                                    <option value="3">待处理</option>
                                </select>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">审核日期：</label>
                            <div class="layui-input-block">
                                <input readonly type="text" name="auditDate" id="auditDate" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">发票代码：</label>
                            <div class="layui-input-block">
                                <input readonly type="text" name="invoiceCode" placeholder="请输入发票代码" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">税额：</label>
                            <div class="layui-input-block">
                                <input readonly type="text" name="taxAmount" placeholder="0.00" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">发票号码：</label>
                            <div class="layui-input-block">
                                <input readonly type="text" name="invoiceNumber" placeholder="请输入发票号码" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="layui-form-item">
                            <label class="layui-form-label">价税合计：</label>
                            <div class="layui-input-block">
                                <input readonly type="text" name="totalIncludingTax" placeholder="0.00" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                    </td>
                </tr>
            </table>

            <div class="form-actions">
                <button class="layui-btn" lay-submit lay-filter="saveBtn">
                    <i class="layui-icon">&#xe608;</i> 保存
                </button>
                <button type="button" class="layui-btn layui-btn-normal" id="cancelBtn">
                    <i class="layui-icon">&#x1006;</i> 取消
                </button>
                <button type="button" class="layui-btn layui-btn-primary" id="auditBtn">
                    <i class="layui-icon">&#xe605;</i> 审核
                </button>
                <button type="button" class="layui-btn layui-btn-danger" id="antiAuditBtn">
                    <i class="layui-icon">&#x1007;</i> 反审核
                </button>
                @* <button type="button" class="layui-btn layui-btn-default" id="collapseBtn"> *@
                @*     <i class="layui-icon">&#xe61a;</i> 收起 *@
                @* </button> *@
            </div>
        </form>

        <div class="material-info-section">
            <div class="section-header">
                <h3>物料信息</h3>
                <button id="add-material-btn" class="btn btn-primary">新增物料</button>
            </div>

            <table class="material-table">
                <thead>
                    <tr>
                        <th width="10">序号</th>
                        <th width="15">采购订单号</th>
                        <th width="15">仓库</th>
                        <th width="15">入库单号</th>
                        <th width="12%">物料编码</th>
                        <th width="10">物料名称</th>
                        <th width="12">型号规格</th>
                        <th width="8">主计量</th>
                        <th width="10">数量</th>
                        <th width="10">单价</th>
                        <th width="10">金额</th>
                        <th width="10">税率</th>
                        <th width="10">税额</th>
                        <th width="8">操作</th>
                    </tr>
                </thead>
                <tbody id="material-tbody">
                    <!-- 动态生成的行会在这里 -->
                </tbody>
            </table>

            <!-- 物料选择模态框 -->
            <div id="material-modal" class="modal">
                <div class="modal-content">
                    <div class="modal-header">
                        <h4>选择物料</h4>
                        <span class="close">&times;</span>
                    </div>
                    <div class="modal-body">
                        <div class="search-bar">
                            <input type="text" id="material-search" placeholder="输入物料编码或名称搜索">
                            <button id="search-btn">搜索</button>
                        </div>
                        <table class="material-select-table">
                            <thead>
                                <tr>
                                    <th>物料编码</th>
                                    <th>物料名称</th>
                                    <th>型号规格</th>
                                    <th>主计量</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="material-select-tbody">
                                <!-- 物料选择数据会在这里 -->
                            </tbody>
                        </table>
                        <div class="pagination">
                            <span>共52条</span>
                            <span>100条/页</span>
                            <span>前往</span>
                            <input type="number" value="1" min="1">
                            <span>页</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <script src="~/lib/layui/layui.js"></script>
    <script>
        // 使用layui模块
        layui.use(['form', 'layer', 'laydate', 'jquery'], function () {
            var form = layui.form;
            var layer = layui.layer;
            var laydate = layui.laydate;
            var $ = layui.$;

            // 初始化日期控件
            laydate.render({
                elem: '#invoiceDate',
                value: new Date(),
                trigger: 'click'
            });

            laydate.render({
                elem: '#auditDate',
                trigger: 'click'
            });
            

            


            // 从sessionStorage获取编辑数据
            var editDataStr = sessionStorage.getItem('LookData');
            console.log("session是：",sessionStorage.getItem('LookData'))
            if(editDataStr) {
                var editData = JSON.parse(editDataStr);
                //在从sessionStorage加载数据时设置peid值
                $('#peid').val(editData.peid); 
                $('#documentCode').val(editData.documentCode);
                $('#invoiceDate').val(editData.invoiceDate);
                $('#supid').val(editData.supid);
                $('#documentStuct').val(editData.documentStuct);
                $('#businessStuct').val(editData.businessStuct);
                $('#taxNumber').val(editData.taxNumber);
                $('#supplierName').val(editData.supplierName);
                $('#invoiceCode').val(editData.invoiceCode);
                $('#auditor').val(editData.auditor);
                $('#invoiceType').val(editData.invoiceType);
                $('#auditDate').val(editData.auditDate);
                $('#invoiceAmount').val(editData.invoiceAmount);
                $('#taxLv').val(editData.taxLv);
                $('#taxAmount').val(editData.taxAmount);
                $('#invoiceNumber').val(editData.invoiceNumber);
                $('#financialStatus').val(editData.financialStatus);
                $('#totalIncludingTax').val(editData.totalIncludingTax);
                // 填充表单数据
                form.val('editForm', { // editForm是表单的lay-filter值
                    "peid": editData.peid,
                    "documentCode": editData.documentCode,
                    "supid":editData.supid,
                    "invoiceDate": editData.invoiceDate ? layui.util.toDateString(editData.invoiceDate, 'yyyy-MM-dd') : '',
                    "documentStuct": editData.documentStuct.toString(),
                    "businessStuct": editData.businessStuct,
                    "taxNumber":editData.taxNumber,
                    "supplierName": editData.supplierName,
                    "invoiceCode": editData.invoiceCode,
                    "auditor":editData.auditor,
                    "invoiceType":editData.invoiceType,
                    "auditDate":editData.auditDate,
                    "invoiceAmount":editData.invoiceAmount,
                    "taxLv": editData.taxLv,
                    "taxAmount": editData.taxAmount,
                    "invoiceNumber":editData.invoiceNumber,
                    "financialStatus":editData.financialStatus,
                    "totalIncludingTax":editData.totalIncludingTax,
                    
                });
                console.log(editData.documentStuct)
                // 渲染表单
                form.render();
            }

            // 监听提交
            form.on('submit(saveBtn)', function(data){
                // 获取表单数据
                var formData = data.field;

                $.ajax({
                    //url: 'http://localhost:5090/api/PurchaseInvoices/EditPurchaseorder',
                    url: "@ViewBag.BaseUrl/T8/PurchaseInvoices/EditPurchaseorder",
                    type: 'POST',
                    data: JSON.stringify(formData),
                    contentType: 'application/json',
                    success: function(res) {
                        console.log("修改数据:",res)
                        if(res.code==206) {
                            layer.msg('修改成功', {icon: 1});
                            // 返回列表页
                            setTimeout(function(){
                                window.location.href = 'GetProcurements'; // 列表页A的路径
                            }, 1000);
                        } else {
                            layer.msg(res.message || '修改失败', {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('请求失败，请稍后再试', {icon: 2});
                    }
                });

                return false; // 阻止表单跳转
            });

           

            // 取消按钮点击事件

            $('#cancelBtn').on('click', function () {
                layer.confirm('确定要取消当前操作吗？', {
                    icon: 3,
                    title: '提示'
                }, function(index) {
                    layer.close(index);
                    location.reload();
                });
            });

            // 审核按钮点击事件
            $('#auditBtn').on('click', function () {
                var peid = $('#peid').val();
                editPurchaseOrderStatus(parseInt(peid));
                console.log("获取到的peid是：", peid); // 调试

                if(!peid || isNaN(peid)) {
                    alert('请提供有效的采购订单ID');
                    return;
                }
            });
            function editPurchaseOrderStatus(peid){
                var requestData = {
                    peid: peid
                };
                console.log("requestData是：",requestData)
                $.ajax({
                    //url: 'http://localhost:5090/api/PurchaseInvoices/EditPurchaseorderStatue',
                    url: "@ViewBag.BaseUrl/T8/PurchaseInvoices/EditPurchaseorderStatue",
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(requestData),
                    success:function(res){
                        console.log("res是：",res)
                        if(res.code==206){
                            alert('审核成功');
                            location.href='GetProcurements'
                        }
                        else{
                            alert('审核失败');
                        }
                    },
                    complete: function() {
                        // 无论成功失败，都恢复按钮状态
                        $('#auditBtn').prop('disabled', false).text('审核');
                    }
                })
            }

            // 反审核按钮点击事件
            $('#antiAuditBtn').on('click', function () {
                layer.confirm('确定要反审核当前发票吗？', {
                    icon: 3,
                    title: '提示'
                }, function(index) {
                    layer.close(index);
                    layer.msg('反审核成功', {icon: 1});
                    $('input[name="documentStatus"]').val('开立');
                    $('input[name="auditor"]').val('');
                    $('input[name="auditDate"]').val('');
                });
            });

            // 模拟选择供应商
            window.selectSupplier = function() {
                layer.open({
                    type: 2,
                    title: '选择供应商',
                    area: ['800px', '500px'],
                    content: '/supplier/select',
                    end: function() {
                        // 回调逻辑
                    }
                });
            };

            form.render();
        });

        // 物料管理相关功能
        document.addEventListener('DOMContentLoaded', function() {
            let rowCount = 0;
            const modal = document.getElementById('material-modal');
            window.currentSelectingRow = { index: null, element: null };

            // 确保按钮存在再绑定事件
            // const addMaterialBtn = document.getElementById('add-material-btn');
            // if (addMaterialBtn) {
            //     addMaterialBtn.addEventListener('click', addMaterialRow);
            // } else {
            //     console.error('未找到按钮: add-material-btn');
            // }

            // 新增物料行
            //function addMaterialRow() {
                rowCount++;
                const tbody = document.getElementById('material-tbody');
                if (!tbody) {
                    console.error('未找到表格体: material-tbody');
                    return;
                }

                const newRow = document.createElement('tr');
                newRow.dataset.index = rowCount;

                newRow.innerHTML = `
                    <td>${rowCount}</td>
                    <td><input type="text" class="order-number" value="手工单据"></td>
                    <td><input type="text" class="warehouse" value="手工单据"></td>
                    <td><input type="text" class="receipt-number" value="手工单据"></td>
                    <td>
                        <div class="material-code-select">
                            <input type="text" class="material-code" placeholder="点击选择" value="663639697555461">
                            <button class="btn-select">选择</button>
                        </div>
                    </td>
                    <td><input type="text" class="material-name" value="模板2" readonly></td>
                    <td><input type="text" class="specification" value="8*8" readonly></td>
                    <td><input type="text" class="unit" value="套" readonly></td>
                    <td><input type="number" class="pcount" value="5" min="0" step="0.01"></td>
                    <td><input type="number" class="price" value="5" min="0" step="0.01"></td>
                    <td><input type="number" class="howmany" value="25.0" min="0" step="0.01"></td>
                    <td><input type="number" class="taxLv" value="1" min="0" step="0.01"></td>
                    <td><input type="number" class="taxAmount" value="0.25" min="0" step="0.01"></td>
                    <td><button class="btn-delete">删除</button></td>
                `;

                // 绑定税率计算事件
                bindTaxCalculation(newRow);

                // 绑定数量和单价计算事件
                bindQuantityPriceCalculation(newRow);

                // 绑定选择按钮事件
                const selectBtn = newRow.querySelector('.btn-select');
                if (selectBtn) {
                    selectBtn.addEventListener('click', function() {
                        window.currentSelectingRow = {
                            index: rowCount,
                            element: newRow
                        };
                        openMaterialModal();
                    });
                }

                // 绑定删除按钮事件
                const deleteBtn = newRow.querySelector('.btn-delete');
                if (deleteBtn) {
                    deleteBtn.addEventListener('click', function() {
                        tbody.removeChild(newRow);
                        updateRowNumbers();
                    });
                }

                tbody.appendChild(newRow);
            //}

            // 绑定税率计算
            function bindTaxCalculation(row) {
                const taxLvInput = row.querySelector('.taxLv');
                const howmanyInput = row.querySelector('.howmany');
                const taxAmountInput = row.querySelector('.taxAmount');

                if (taxLvInput && howmanyInput && taxAmountInput) {
                    taxLvInput.addEventListener('input', function() {
                        const amount = parseFloat(howmanyInput.value) || 0;
                        const taxRate = parseFloat(taxLvInput.value) / 100 || 0;
                        taxAmountInput.value = (amount * taxRate).toFixed(2);
                    });
                }
            }

            // 绑定数量和单价计算
            function bindQuantityPriceCalculation(row) {
                const pcountInput = row.querySelector('.pcount');
                const priceInput = row.querySelector('.price');
                const howmanyInput = row.querySelector('.howmany');

                if (pcountInput && priceInput && howmanyInput) {
                    const calculate = function() {
                        const quantity = parseFloat(pcountInput.value) || 0;
                        const unitPrice = parseFloat(priceInput.value) || 0;
                        howmanyInput.value = (quantity * unitPrice).toFixed(2);
                    };

                    pcountInput.addEventListener('input', calculate);
                    priceInput.addEventListener('input', calculate);
                }
            }

            // 打开物料选择模态框
            function openMaterialModal() {
                if (modal) {
                    modal.style.display = 'block';
                    loadMaterialData();
                } else {
                    console.error('找不到模态框元素');
                }
            }

            // 关闭模态框
            const closeBtn = document.querySelector('.close');
            if (closeBtn) {
                closeBtn.addEventListener('click', function() {
                    if (modal) modal.style.display = 'none';
                });
            }

            // 窗口点击关闭模态框
            window.addEventListener('click', function(event) {
                if (event.target === modal) {
                    modal.style.display = 'none';
                }
            });

            // 加载物料数据
            function loadMaterialData(searchParams = {}) {
                const tbody = document.getElementById('material-select-tbody');
                if (!tbody) {
                    console.error('未找到物料选择表格体');
                    return;
                }

                tbody.innerHTML = '';

                const queryParams = new URLSearchParams();
                if (searchParams.material_code) queryParams.append('material_code', searchParams.material_code);
                if (searchParams.material_name) queryParams.append('material_name', searchParams.material_name);

                fetch(`@ViewBag.BaseUrl/T7/Materials/GetMaterial_Basic?${queryParams.toString()}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 0 && data.data) {
                            data.data.forEach(material => {
                                const row = document.createElement('tr');
                                row.innerHTML = `
                                    <td>${material.material_code}</td>
                                    <td>${material.material_name}</td>
                                    <td>${material.model_specification}</td>
                                    <td>${material.unit_of_measurement_name}</td>
                                    <td><button class="btn-choose">选择</button></td>
                                `;

                                const chooseBtn = row.querySelector('.btn-choose');
                                if (chooseBtn) {
                                    chooseBtn.addEventListener('click', function() {
                                        selectMaterial(material);
                                    });
                                }

                                tbody.appendChild(row);
                            });
                        } else {
                            console.error('获取物料数据失败:', data.msg);
                        }
                    })
                    .catch(error => {
                        console.error('获取物料数据出错:', error);
                    });
            }

            // 选择物料
            function selectMaterial(material) {
                if (!window.currentSelectingRow?.element) {
                    console.error('没有选中的行或元素不存在');
                    return;
                }

                const row = window.currentSelectingRow.element;
                const inputs = {
                    code: row.querySelector(".material-code"),
                    name: row.querySelector(".material-name"),
                    spec: row.querySelector(".specification"),
                    unit: row.querySelector(".unit"),
                    orderNumber: row.querySelector(".order-number"),
                    warehouse: row.querySelector(".warehouse"),
                    receiptNumber: row.querySelector(".receipt-number")
                };

                if (inputs.code && inputs.name && inputs.spec && inputs.unit) {
                    inputs.code.value = material.material_code || '';
                    inputs.name.value = material.material_name || '';
                    inputs.spec.value = material.model_specification || '';
                    inputs.unit.value = material.unit_of_measurement_name || '';

                    if (inputs.orderNumber) inputs.orderNumber.value = '手工单据';
                    if (inputs.warehouse) inputs.warehouse.value = '手工单据';
                    if (inputs.receiptNumber) inputs.receiptNumber.value = '手工单据';

                    // 触发输入事件
                    Object.values(inputs).forEach(input => {
                        if (input) input.dispatchEvent(new Event('input'));
                    });
                } else {
                    console.error('部分输入元素未找到');
                }

                if (modal) modal.style.display = 'none';
            }

            // 更新行号
            function updateRowNumbers() {
                const tbody = document.getElementById('material-tbody');
                if (!tbody) return;

                const rows = tbody.querySelectorAll('tr');
                rows.forEach((row, index) => {
                    const firstCell = row.cells[0];
                    if (firstCell) {
                        firstCell.textContent = index + 1;
                        row.dataset.index = index + 1;
                    }
                });
                rowCount = rows.length;
            }

            // 搜索功能
            const searchBtn = document.getElementById('search-btn');
            if (searchBtn) {
                searchBtn.addEventListener('click', function() {
                    const searchInput = document.getElementById('material-search');
                    if (searchInput) {
                        const searchText = searchInput.value.trim();
                        const searchParams = searchText ?
                            (isNaN(searchText) ? { material_name: searchText } : { material_code: searchText })
                            : {};
                        loadMaterialData(searchParams);
                    }
                });
            }

            // 初始化加载一些数据（可选）
            loadMaterialData();
        });
    </script>
</body>
</html>